//
//  KLMAllDevicesController.swift
//  KLM_GN
//
//  Created by Nic on 2025/2/20.
//  家中所有设备 ｜ 家中某个房间所有设备

import UIKit
import nRFMeshProvision

private let cellId = String(describing: KLMDeviceListCell.self)

/// 设备列表（家中｜房间中）
enum AllDeviceType {
    case home
    case homeRoom
}


class KLMAllDevicesController: KLMBaseController {
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    weak var navRightBtn: UIButton?
    private lazy var deviceList = [KLMHomeDevice]() {
        didSet {
            navRightBtn?.isHidden = deviceList.count == 0
            
            if deviceList.count > 0 {
                hideEmptyState()
            } else {
                showEmptyState(title: "暂无设备", buttonTitle: "添加设备")
            }
        }
    }
    var roomName: String?
    private var listType: AllDeviceType = .home
    private var homeId: Int?
    private var homeRoom: KLMHomeRoom?
    
    init(listType: AllDeviceType = .home, homeId: Int? = nil, homeRoom: KLMHomeRoom? = nil) {
        self.listType = listType
        self.homeId = homeId
        self.homeRoom = homeRoom
        super.init(nibName: "KLMAllDevicesController", bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = rgba(243, 243, 246, 1)
        collectionView.backgroundColor = rgba(243, 243, 246, 1)
        
        let rightItem = KLMBaseButton()
        navRightBtn = rightItem
        navigationItem.rightBarButtonItem = UIBarButtonItem.itemWithBaseButton(rightItem, target: self, action: #selector(tapAddDevice(_:)), configBlock: { baseItem in
            baseItem.configStyle(image: "add")
        })
        showEmptyState(title: "暂无设备", buttonTitle: "添加设备")
        navRightBtn?.isHidden = deviceList.count == 0
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadDeviceList()
    }
    
    // MARK: - 查询设备列表
    func loadDeviceList() {
        if let homeId = getNewestHomeId(homeId: self.homeId) {
            guard let homeRoomId = homeRoom?.homeRoomId else {
                /// 无房间ID，查询家中所有的设备列表
                KLMRequest.queryHomeDeviceList(meshId: homeId) { response in
                    
                    if let list = response as? [KLMHomeDevice] {
                        self.deviceList = list
                        self.collectionView.reloadData()
                    }
                } failure: { error in
                    KLMHttpShowError(error)
                }
                return
            }
            /// 查询家中房间所有设备
            KLMRequest.queryHomeRoomDeviceList(meshId: homeId, homeRoomId: homeRoomId) { response in
                
                if let list = response as? [KLMHomeDevice] {
                    self.deviceList = list
                    self.collectionView.reloadData()
                }
            } failure: { error in
                KLMHttpShowError(error)
            }
        }
    }
    
    override func viewDidLoadConfig() {
        super.viewDidLoadConfig()
        
        let layout = KLMCustomFlowLayout()
        layout.cellCountPerRow = 1
        layout.itemSize = CGSizeMake(200, 94)
        collectionView.collectionViewLayout = layout
        
        collectionView.register(UINib(nibName: cellId, bundle: nil), forCellWithReuseIdentifier: cellId)
        collectionView.delegate = self
        collectionView.dataSource = self
    }
    
    override func tapEmptyButton(_ button: UIButton) {
        // 添加设备
        tapAddDevice(nil)
    }
    
    @IBAction @objc func tapAddDevice(_ sender: UIButton?) {
        /// 判断权限
        KLMHomeMesh.canEditMesh { [weak self] in
            guard let self = self else {return }
            let addVc = KLMAddDeviceController(homeRoomId: homeRoom?.homeRoomId)
            addVc.titleText = "添加设备"
            self.navigationController?.pushViewController(addVc, animated: true)
            
        } failure: {
            
        }
    }
    
    override func showEmptyButton() -> Bool {
        true
    }
    
    // MARK: - 配置设备参数，设备开关
    func onOffDevice(isOn: Bool, at indexPath: IndexPath) {
        
        KLMHomeMesh.canEditMesh {[weak self] in
            guard let self = self else {return }
            
            let ledEnable = isOn == true ? 1 : 0
            let device = self.deviceList[indexPath.item]
            SVProgressHUD.show()
            KLMRequest.configRKDeviceProfile(meshId: device.meshId, uuid: device.uuid, configDict: ["ledEnable" : ledEnable]) { response in
                SVProgressHUD.dismiss()
                self.loadDeviceList()
                
            } failure: { error in
                SVProgressHUD.dismiss()
                KLMHttpShowError(error)
            }
        } failure: {
            
        }
    }
}

extension KLMAllDevicesController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return deviceList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! KLMDeviceListCell
        cell.deviceInfo = deviceList[indexPath.item]
        cell.onOffBlcok = { [weak self] isOn in
            guard let self = self else { return }
            self.onOffDevice(isOn: isOn, at: indexPath)
        }
        return cell
    }
}

extension KLMAllDevicesController: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // 设备设置页面
        let info = deviceList[indexPath.item]
        // 获取节点
        if let network = MeshNetworkManager.instance.meshNetwork {
            if let node = network.nodes.first(where: { $0.nodeuuidString == info.uuid }) {
                
                print("network的节点：", node.nodeName)
                // 记录当前节点
                KLMHomeManager.sharedInstacnce.smartNode = node
                
                let settingVc = KLMDeviceSettingController(info: info)
                settingVc.titleText = KLMLocalizable.LANGLOC("Settings")
                navigationController?.pushViewController(settingVc, animated: true)
            }
        }
    }
}
